package zjh.msg.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import zjh.msg.entity.Msg;
import zjh.msg.entity.MsgDto;
import zjh.msg.entity.MsgVo;
import zjh.msg.service.MsgService;

import java.util.List;

@Controller
@RequestMapping("msg")
public class MsgController {

    @Autowired
    MsgService msgService;

    @GetMapping
    public ModelAndView msg(@RequestParam(required = false, defaultValue = "1") Integer pageNo,
                            @RequestParam(required = false, defaultValue = "5") Integer pageSize){
        PageHelper.startPage(pageNo,pageSize);
        List<MsgVo> msgVoList = msgService.pageList();
        PageInfo<MsgVo> msgVoPageInfo = new PageInfo<>(msgVoList);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msgList", msgVoList);
        modelAndView.addObject("pageInfo",msgVoPageInfo);
        modelAndView.setViewName("msg");
        return modelAndView;
    }

    @PostMapping("save")
    @Transactional(rollbackFor = Exception.class)
    public String save(MsgDto msgDto) {
        msgService.save(msgDto);
        return "redirect:/msg";
    }

    @PostMapping("delete")
    @Transactional(rollbackFor = Exception.class)
    public String delete(@RequestParam Integer id) {
        msgService.delete(id);
        return "redirect:/msg";
    }
}
